<template>
  <div class="accept">
    <div class="header">
      <div class="inner">
        <h5>
          我是
          <span>{{inviter.wxNickName||'小旺仔'}}</span>
        </h5>
        <p>邀请您无门槛成为旺仔旺铺CEO会员， 和我一起推广旺旺商品赚奖金！</p>
      </div>
    </div>
    <div class="main">
      <div class="inner">
        <div class="form">
          <div class="form-inner">
            <div class="input">
              <div class="inner">
                <label>
                  <img
                    src="../../../assets/images/form_label_phone.png"
                    style="transform:translateX(3px)"
                    alt="label"
                  >
                </label>
                <input
                  name="手机号"
                  v-validate="'required|digits:11'"
                  type="tel"
                  v-model="formData.phone"
                  placeholder="请输入手机号"
                  @blur="RTverity"
                  @keypress="RTverityInfoPhone=''"
                  @change="RTverityInfoPhone=''"
                >
              </div>
              <span
                v-if="errors.first('手机号')||RTverityInfoPhone"
                class="error-info"
              >{{ RTverityInfoPhone||errors.first('手机号') }}</span>
            </div>
            <div class="input">
              <div class="inner">
                <label>
                  <img
                    src="../../../assets/images/form_label_id.png"
                    alt="label"
                    style="height:11px"
                  >
                </label>
                <input
                  name="图形验证码"
                  v-validate="'required'"
                  type="text"
                  placeholder="图形验证码"
                  v-model="formData.imgCode"
                >
              </div>
              <div class="imgCode">
                <i :style="{backgroundImage:'url('+imgCode.img+')'}"></i>
              </div>
              <span
                v-if="RTverityInfoImgCode||errors.first('图形验证码')"
                class="error-info"
              >{{ RTverityInfoImgCode||errors.first('图形验证码') }}</span>
            </div>
            <div class="input">
              <div class="inner">
                <label>
                  <img src="../../../assets/images/form_label_license.png" style="height:11px">
                </label>
                <input
                  name="验证码"
                  v-validate="'required|numeric'"
                  type="tel"
                  placeholder="短信验证码"
                  @blur="RTverity"
                  v-model="formData.phoneCode"
                >
              </div>
              <div :class="['sender',senderAble?'':'disable']" @click="verityImgCode">
                <span>{{getCodeCounter||senderInfo}}</span>
              </div>
              <span
                v-if="errors.first('验证码')||RTverityInfoCoder"
                class="error-info"
              >{{ RTverityInfoCoder||errors.first('验证码') }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="button" @click="submit">
        <span>接受邀请</span>
      </div>
    </div>
    <div class="footer">
      <div class="inner">
        <div class="title">
          <span>活动说明</span>
        </div>
        <ol class="content">
          <li v-for="(item, index) in instructions" :key="index">
            <span>{{item}}</span>
          </li>
        </ol>
      </div>
    </div>
    <div class="texture">
      <i v-for="(item, index) in 7" :key="index"></i>
    </div>
  </div>
</template>

<script>
import store from "../../../store.js";
import axios from "axios";

axios.defaults.withCredentials = true;

export default {
  data() {
    return {
      senderInfo: "获取验证码",
      senderAble: true,
      RTverityInfoPhone: "",
      RTverityInfoCoder: "",
      RTverityInfoImgCode: "",
      getCodeCounter: null,
      imgCode: {
        img: "static/images/jdj_login_imgCode.jpg",
        code: "m8k2"
      },
      formData: {
        phone: "",
        imgCode: "",
        phoneCode: ""
      },
      loginResult: "",
      instructions: [
        "输入手机号，点击接受邀请，即可获得旺仔旺铺CEO会员资格，每个手机号限注册一次。",
        "邀请好友无门槛成为CEO会员的权限是特别开放给金犊奖-旺仔旺铺特别营销项目参赛者的，仅限10个名额，额满即止。",
        "该活动邀请好友对象只针对非CEO会员",
        "被邀请者成为会员后，即作为参赛者的团队成员，所产生的推广业绩会影响参赛者的比赛成绩，鼓励多多推广。",
        "下载旺仔旺铺APP后用所注册的手机号登录，即可享受会员权益。",
        "旺仔旺铺保留法律范围内允许的对活动的解释权。"
      ]
    };
  },
  computed: {
    serveAPI: {
      get() {
        let serve = {};
        let portAddress = store.state.apiPort.map(
          e => store.state.apiOrigin + e.split(":")[1]
        );
        let portName = store.state.apiPort.map(e => e.split(":")[0]);
        for (let i = 0; i < portName.length; i++) {
          serve[portName[i]] = portAddress[i];
        }
        return serve;
      },
      set() {}
    },
    calfKey: {
      get() {
        return store.state.calfKey;
      },
      set() {}
    },
    inviter: {
      get() {
        return store.state.inviter;
      },
      set() {}
    },
    lifeInfo: {
      get() {
        return store.state.lifeInfo;
      },
      set() {}
    },
    wxEnv: {
      get() {
        return store.state.wxEnv;
      },
      set() {}
    },
    wxApp: {
      get() {
        return store.state.wxApp;
      },
      set() {}
    }
  },
  methods: {
    //----------------------------------------------------
    // default
    init() {
      setTimeout(() => {
        store.commit("upload", { prope: "loaded", data: true });
      }, 800);
      this.getImgCode();
      this.getInvited();
    },
    close() {
      store.commit("upload", { prope: "loginState", data: false });
      this.loginResult = "";
    },
    cleanState() {
      window.scrollTo(0, 0);
      let inputList = [...document.querySelectorAll("input")];
      inputList.map(e => {
        e.blur();
      });
    },

    //----------------------------------------------------
    // verity
    RTverity(e) {
      if (this.dev) return;
      this.$validator.validate(e.target.name).then(result => {
        if (result) {
          if (e.target.name === "手机号") this.verityPhone();
          if (e.target.name === "验证码") {
            this.$validator.validate("手机号").then(result => {
              if (result && !this.RTverityInfoPhone) {
                this.verityCode();
              }
            });
          }
        }
      });
    },
    verityPhone() {
      this.$validator.validate("手机号").then(result => {
        if (result) {
          axios
            .get(this.serveAPI.verityPhoneInvited + this.formData.phone)
            .then(res => {
              // console.log(res);
              if (res.data.error) {
                this.RTverityInfoPhone = res.data.error;
              }
            });
          // this.verityImgCode();
        }
      });
    },

    verityImgCode() {
      if (!this.senderAble || this.RTverityInfoPhone) return;
      this.$validator.validate("图形验证码").then(result => {
        if (result) {
          axios
            .post(this.serveAPI.verityImgCode, {
              mobileNumber: this.formData.phone,
              captcha: this.formData.imgCode
            })
            .then(res => {
              // console.log(res)
              if (res.data.Response.code != 10001) {
                this.RTverityInfoImgCode = "图形验证码错误";
                this.getImgCode();
              } else {
                this.RTverityInfoImgCode = "";
                this.getPhoneCode();
              }
            });
        }
      });
    },
    verityCode() {
      if (!this.formData.phone || !this.formData.phoneCode) return;
      axios
        .get(
          this.serveAPI.verityCode +
            this.formData.phone +
            "/" +
            this.formData.phoneCode
        )
        .then(response => {
          // console.log(response);
          if (response.data.error) {
            this.RTverityInfoCoder = "验证码不匹配";
          } else {
            this.RTverityInfoCoder = "";
          }
        });
    },
    verityWx() {
      let href = window.location.href;
      if (href.match("code=")) {
        // alert('当前链接：' + href)
        let code = href.split("code=")[1].split("&")[0];
        // alert("获取到的code：" + code);
        axios.get(this.serveAPI.wxLoginInvite + code).then(res => {
          // alert('授权信息' + JSON.stringify(res.data.object))
          this.submitCore(
            this.cookieGet("invited").split("&")[0],
            this.cookieGet("invited").split("&")[1]
          );
          if (res.data.error) alert(res.data.error);
        });
      } else {
        // alert('进行显式授权')
        window.location.href =
          "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
          this.wxApp.appId +
          "&redirect_uri=" +
          encodeURIComponent(href) +
          "&response_type=code&scope=" +
          this.wxApp.scopeInfo +
          "#wechat_redirect&connect_redirect=1";
      }
    },
    verityWxEnv() {
      let ua = window.navigator.userAgent;
      return /MicroMessenger/.test(ua);
    },
    //----------------------------------------------------
    // serve
    getImgCode() {
      axios.get(this.serveAPI.getImgCode).then(res => {
        // console.log(res.data.Response)
        this.imgCode = {
          img: "data:image/jpeg;base64," + res.data.Response.data,
          code: res.data.Response.code
        };
      });
    },
    getPhoneCode() {
      this.$validator.validate("手机号").then(result => {
        if (result && !this.RTverityInfoPhone) {
          this.$validator.validate("图形验证码").then(result => {
            if (result && !this.RTverityInfoImgCode) {
              axios
                .post(this.serveAPI.getCode, {
                  mobileNumber: this.formData.phone
                })
                .then(() => {
                  alert("已发送");
                  this.getCodeCountTimer(60);
                })
                .catch(err => {
                  alert(JSON.stringify(err));
                  this.senderInfo = "获取失败";
                  this.senderAble = false;
                });
            }
          });
        }
      });
    },

    submit() {
      if (this.lifeInfo || !this.wxEnv) {
        alert(this.lifeInfo || "请在微信内打开");
      } else {
        this.verityCode();
        this.cleanState();
        setTimeout(() => {
          this.$validator.validateAll().then(result => {
            if (
              result &&
              !this.RTverityInfoPhone &&
              !this.RTverityInfoCoder &&
              !this.RTverityInfoImgCode
            ) {
              // 本地存储被邀请人信息
              // alert('本地存储被邀请人信息：' + this.formData.phone + '&' + this.calfKey)
              this.cookieSet(
                "invited",
                this.formData.phone + "&" + this.calfKey
              );
              // 微信验证相关
              if (this.verityWxEnv()) {
                // 微信环境判断
                // alert('进入微信授权')
                this.verityWx();
              }
            }
          });
        }, 500);
      }
    },
    submitCore(phone, key) {
      this.cookieSet("invited", "");
      axios
        .post(this.serveAPI.register, {
          mobileNumber: phone,
          calfKey: key
        })
        .then(res => {
          if (res.data.error) {
            alert(JSON.stringify(res.data.error));
          } else {
            // alert(JSON.stringify(res))
            store.commit("upload", { prope: "register", data: true });
            store.commit("upload", { prope: "registerState", data: true });
          }
        });
    },
    getInvited() {
      if (this.cookieGet("invited")) {
        // alert(this.cookieGet("invited"))
        this.verityWx();
      }
    },
    //----------------------------------------------------
    // cookie
    cookieGet(key) {
      key = key + "=";
      let cookieList = document.cookie.split(";");
      for (let i = 0; i < cookieList.length; i++) {
        const item = cookieList[i].trim();
        if (item.indexOf(key) == 0)
          return item.substring(key.length, item.length);
      }
      return;
    },
    cookieSet(key, value, day) {
      let d = new Date();
      d.setTime(d.getTime() + day * 24 * 60 * 60 * 1000);
      let expires = "expires=" + d.toGMTString();
      document.cookie = key + "=" + value + ";" + expires;
    },
    //----------------------------------------------------
    // getPhoneCode counter
    getCodeCountTimer(e) {
      if (e) this.getCodeCounter = 60;
      this.senderAble = false;
      if (this.getCodeCounter > 0) {
        this.getCodeCount();
      } else {
        this.getCodeCounter = null;
        this.senderAble = true;
      }
    },
    getCodeCount() {
      setTimeout(() => {
        this.getCodeCounter--;
        this.getCodeCountTimer();
      }, 1000);
    }
  },
  mounted() {
    this.init();
  }
};
</script>
<style lang='stylus' scoped>
@import '../../../assets/styles/index.styl'
.accept {
  background linear-gradient(to bottom, #f85f5d, #fd866f, #ffa37f, #ff725d)
  width 100%
  overflow hidden
  position relative
  .header {
    &:before {
      content ''
      display block
      width 100%
      height 190px
      background-image url('../../../assets/images/jdj_accept_header_main.png')
      background-size auto 100%
      background-position center
      background-repeat no-repeat
      position relative
      z-index 2
    }
    .inner {
      position relative
      z-index 1
      top -7px
      background #000
      width 70%
      margin 0 auto
      border-radius 15px
      background linear-gradient(45deg, #ff5d70, #ff8974)
      border 3px solid #f5e4ca
      box-shadow 1px 1px 5px rgba(203, 55, 31, 0.6)
      color #fff
      padding 15px 10px
      h5 {
        font-weight normal
        font-size 14px
        margin-bottom 3px
        span {
          font-weight bold
        }
      }
      p {
        font-size 12px
        line-height 18px
      }
    }
  }
  .main {
    width 85%
    margin 15px auto
    position relative
    &:before, &:after {
      content ''
      display inline-block
      position absolute
      left 0
      bottom 0
      width 100%
      border-radius 12px
      height 80%
      z-index 0
      background c8 // linear-gradient(to bottom, #ffae78, #ff7161)
      box-shadow 1px 1px 10px rgba(245, 33, 61, 0.5)
    }
    &:after {
      height 35%
      z-index 3
      background url('../../../assets/images/jdj_accept_main_form_footer.png')
      background-position center bottom
      background-size 100% auto
      background-repeat no-repeat
      box-shadow 0px 0px 0px #000
      border-radius 0px
      opacity 1
      bottom 0px
    }
    &>.inner {
      position relative
      z-index 1
      text-align center
      .form {
        padding 15px
        background #fff
        width 93%
        display inline-block
        border-radius 10px
        position relative
        box-sizing border-box
        &:before, &:after {
          content ''
          display inline-block
          height 16px
          width 16px
          position absolute
          top 40%
          left 0
          background c8
          border-radius 50%
          left -8px
        }
        &:after {
          left unset
          right -8px
        }
        .form-inner {
          padding-bottom 80px
          .input {
            position relative
            margin 10px 0px
            text-align left
            .inner {
              border 1px solid rgba(0, 0, 0, 0.03)
              border-radius 5px
              position relative
              display inline-block
              padding-left 30px
              width 100%
              box-sizing border-box
              label {
                font-size 14px
                display inline-block
                height 16px
                position absolute
                left 8px
                top 50%
                transform translateY(-55%)
                img {
                  vertical-align middle
                  height 100%
                  width auto
                }
              }
              input {
                outline 0
                border 0
                width 100%
                padding 15px 0px 15px 5px
                font-size 14px
                display inline-block
                background rgba(0, 0, 0, 0)
              }
            }
            &:nth-child(2), &:nth-child(3) {
              .inner {
                width 60%
              }
            }
          }
          .imgCode {
            display inline-block
            position relative
            border 1px solid rgba(0, 0, 0, 0.03)
            border-radius 5px
            height 48px
            float right
            width 35%
            padding 8px
            box-sizing border-box
            & i {
              background-size contain
              background-position center
              background-repeat no-repeat
              display inline-block
              height 100%
              width 100%
            }
          }
          .sender {
            display inline-block
            position relative
            border-radius 5px
            height 48px
            line-height 40px
            text-align center
            float right
            width 35%
            padding 5px
            box-sizing border-box
            background c10
            span {
              font-size 13px
              color #fff
            }
            &.disable {
              background #aaa
            }
          }
          .error-info {
            text-align left
            display block
            font-size 12px
            color c5
            padding 5px 0
          }
        }
      }
    }
    .button {
      position absolute
      bottom 15px
      left 50%
      transform translateX(-50%)
      z-index 4
      background-image url('../../../assets/images/button.png')
      height 70px
      background-size contain
      background-repeat no-repeat
      background-position center
      display inline-block
      width 80%
      text-align center
      span {
        position relative
        top 25%
        transform translateY(-50%)
        font-size 18px
        font-weight bold
        color #fff
      }
    }
  }
  .footer {
    .inner {
      color #fff
      padding 25px
      padding-top 5px
      .title {
        font-size 20px
        text-align center
        font-weight bold
        &:before, &:after {
          margin 0 10px
          content ''
          display inline-block
          width 30px
          height 10px
          background-image url('../../../assets/images/jdj_accept_footer_tit_dec.png')
          background-size contain
          background-repeat no-repeat
          background-position center
        }
        &:after {
          transform rotate(180deg)
        }
      }
      .content {
        padding-left 15px
        margin-top 15px
        li {
          list-style decimal
          font-size 12px
          margin-bottom 5px
        }
      }
    }
  }
  .texture {
    i {
      position absolute
      z-index 0
      display block
      &:nth-child(1) {
        height 350px
        width 350px
        background c11
        border-radius 50%
        opacity 0.3
        top -280px
        left -30px
      }
      &:nth-child(2) {
        height 150px
        width 150px
        background linear-gradient(to bottom, c8, rgba(255, 255, 255, 0))
        border-radius 50%
        opacity 0.3
        top 300px
        left -80px
      }
      &:nth-child(3) {
        height 180px
        width 180px
        background linear-gradient(to bottom, c8, rgba(255, 255, 255, 0))
        border-radius 50%
        opacity 0.5
        top 220px
        right -90px
      }
      &:nth-child(4) {
        height 50px
        width 150px
        top 50px
        left -60px
        background-image url('../../../assets/images/jdj_accept_texture_dec_1.png')
        background-size contain
        background-repeat no-repeat
        background-position center
        transform rotate(50deg)
        opacity 0.2
      }
      &:nth-child(5) {
        height 50px
        width 150px
        top 60px
        left 100px
        background-image url('../../../assets/images/jdj_accept_texture_dec_1.png')
        background-size contain
        background-repeat no-repeat
        background-position center
        transform rotate(0deg) scale(0.7)
        opacity 0.2
      }
      &:nth-child(6) {
        height 50px
        width 150px
        top 120px
        right -100px
        background-image url('../../../assets/images/jdj_accept_texture_dec_1.png')
        background-size contain
        background-repeat no-repeat
        background-position center
        transform rotate(-30deg) scale(-1)
        opacity 0.15
      }
      &:nth-child(7) {
        height 50px
        width 150px
        top 60px
        right 0px
        background-image url('../../../assets/images/jdj_accept_texture_dec_2.png')
        background-size contain
        background-repeat no-repeat
        background-position center
        transform rotate(0deg) scale(1)
        opacity 1
      }
    }
  }
}
</style>
